package test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
GET/sample.jsp HTTP/1.1
Accept:image/gif.image/jpeg,*
Accept-Language:zh-cn
Connection:Keep-Alive
Host:localhost
User-Agent:Mozila/4.0(compatible;MSIE5.01;Window NT5.0)
Accept-Encoding:gzip,deflate
 
username=jinqiao&password=1234
*/
public class HttpClient {
	public static void main(String[] args) {
		System.out.println("--->");
		String uri="index.html";
		if(args.length !=0){
			uri=args[0];
		}
		doGet("localhost", 8080, uri);
	}
	public  static void doGet(String host,int port,String uri){
		Socket socket=null;
		try {
			 socket=new Socket(host, port);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			StringBuffer sb=new StringBuffer("GET "+uri+" HTTP/1.1\r\n");
			sb.append("Accept:*/*\r\n");
			sb.append("Accept-Language:zh-cn\r\n");
			sb.append("Accept-Encoding:gzip,deflate\r\n");
			sb.append("User-Agent:HTTPClient\r\n");
			sb.append("Host:localhost:8080\r\n");
			sb.append("Connection:Keep-Alive\r\n\r\n");
			OutputStream socketOut=socket.getOutputStream();
			socketOut.write(sb.toString().getBytes());
			
			Thread.sleep(2000);
			

			InputStream socketIn=socket.getInputStream();
			int size=socketIn.available();
			byte [] buffer=new byte[size];
			socketIn.read(buffer);
			System.out.println(new String(buffer));
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}